package com.comunity_cloud.client.model.file_list;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.comunity_cloud.client.model.Configuration;
import com.comunity_cloud.client.model.MainModel2;
import com.comunity_cloud.client.model.communication.ConnectionsManager;
import com.comunity_cloud.client.model.communication.PacketListener;
import com.comunity_cloud.client.model.communication.PeerConnection;
import com.comunity_cloud.client.model.communication.packet.PeerPacket;
import com.comunity_cloud.client.model.communication.packet.PeerPacketHeader.Type;
import com.comunity_cloud.client.model.file_list.SendMeFilesResponse.FileInfo;
import com.comunity_cloud.client.model.upload_file.FileChunkHeader;
import com.user_hosted_storage.dto.CommunityDTO;

public class FileListServer implements PacketListener<SendMeFilesHeader>{

	public FileListServer() {
		PeerConnection.addPacketListener(Type.SEND_ME_FILES, this);
		
	}
	
	
	
	@Override
	public void packetReceived(PeerPacket<SendMeFilesHeader> peerPacket) {
		try {
			SendMeFilesHeader header = peerPacket.getHeader();
			PeerConnection peerConnection = ConnectionsManager.getInstance().getPeerConnection(peerPacket.getClientId());
			
			CommunityDTO community = MainModel2.getInstance().getCommunity(header.getCommunityId());
			
			File communityHostedDir = new File(Configuration.getInstance().hostedFilesPath+community.getName());
			communityHostedDir.mkdirs();
			File[] files = communityHostedDir.listFiles();
			
			byte[] chunkHeaderBytes = new byte[FileChunkHeader.SIZE];
			FileChunkHeader fileChunkHeader = new FileChunkHeader();
			
			SendMeFilesResponse sendMeFilesResponse = new SendMeFilesResponse();
			PeerPacket<SendMeFilesResponse> responsePacket = new PeerPacket<SendMeFilesResponse>(sendMeFilesResponse, null);
			
			for (File file : files) {
				if(file.getName().equals(".tmp")) {
					continue;
				}
				FileInputStream in = new FileInputStream(file);
				int read = in.read(chunkHeaderBytes);
				if(read < chunkHeaderBytes.length) {
					in.close();
					continue;
				}
				
				in.close();
				
				fileChunkHeader.fromBytes(chunkHeaderBytes);
				
				sendMeFilesResponse.setCommunityId(community.getId());
				FileInfo fileInfo = new FileInfo();
				fileInfo.fileName = file.getName().replaceFirst(""+fileChunkHeader.getTotalOffset(), "");
				fileInfo.fileSize = fileChunkHeader.getTotalSize();
				fileInfo.chunkSize = file.length() - FileChunkHeader.SIZE;
				fileInfo.totalOffset = fileChunkHeader.getTotalOffset();
				fileInfo.isPrimary = fileChunkHeader.isPrimary();				
				sendMeFilesResponse.addFile(fileInfo);
				
			}
			peerConnection.sendPacket(responsePacket);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	

}
